/**
 * 辖区管理
 */
import { Op } from 'sequelize'
import _ from "lodash"
import BaseBusinessController from './../base/BaseBusinessController'

class AdminRegionController extends BaseBusinessController {

    /**
     * 辖区列表
     * @return {[type]} [description]
     */
    async actionColumn() {
        let {province, city, area, street, address} = $_POST

        let where = {};
        if(province){
            where['province'] = province
        }
        if(city){
            where['city'] = city
        }
        if(area){
            where['area'] = area
        }
        if(street){
            where['street'] = street
        }
        if(address){
            where['address'] = {
                [Op.like]: `%${address}%`
            }
        }

        return await this.modules('Region').where(where).fields(['id', 'province', 'city', 'area', 'street','province_name','city_name','area_name','street_name']).order([
            ['id', 'DESC']
        ]).select();
    }

    /**
     * 辖区列表
     * @return {[type]} [description]
     */
    async actionIndex() {
        let {number,size} = super._getPage();

        let {province, city, area, street, address} = $_POST

        let where = {};
        if(province){
            where['province'] = province
        }
        if(city){
            where['city'] = city
        }
        if(area){
            where['area'] = area
        }
        if(street){
            where['street'] = street
        }
        if(address){
            where['address'] = {
                [Op.like]: `%${address}%`
            }
        }

        let regions = await this.modules('Region').where(where).page(number, size).order([['id', 'DESC']]).select(false, {raw: true});

        for(let region of regions.children){
            let admins = await db.sql("select r.id, r.user_name from hz_account_region ar INNER JOIN hz_account r ON r.id = ar.account_id AND r.is_disable = 0 WHERE ar.region_id = :region_id", {region_id: region.id});

            if(_.isArray(admins) && admins.length > 0){
                region['admins'] = admins
                let adminNames = '';
                for(let admin of admins){
                    adminNames += `${admin.user_name};`
                }
                region['adminNames'] = adminNames
            }else{
                region['admins'] = []
            }

            // P(region)

            // let codes = []
            // if(region['province']){
            //     codes.push(region['province'])
            // }
            // if(region['city']){
            //     codes.push(region['city'])
            // }
            // if(region['area']){
            //     codes.push(region['area'])
            // }
            // if(region['street']){
            //     codes.push(region['street'])
            // }

            // let result = await db.sql("select level,name from hz_area WHERE code IN (:codes)", {codes});
            // for(let r of result){
            //     if(r.level === ORG_LEVEL.PROVINCE){
            //         region['provinceName'] = r.name
            //     }
            //     if(r.level === ORG_LEVEL.CITY){
            //         region['cityName'] = r.name
            //     }
            //     if(r.level === ORG_LEVEL.AREA){
            //         region['areaName'] = r.name
            //     }
            //     if(r.level === ORG_LEVEL.TOWN){
            //         region['streetName'] = r.name
            //     }
            // }
        }
        return regions;
    }

    /**
     * 辖区详情
     * @return {[type]} [description]
     */
    async actionView() {
        let id = $_POST['id'];
        let data = await this.modules('Region').where({ id }).first();
        if (data) {
            return data;
        } else {
            throw new Error('数据不存在');
        }
    }

    /**
     * 新增辖区
     * @return {[type]} [description]
     */
    async actionCreate() {
        let {province, city, area, street, account_ids} = $_POST;
        let check = await this.modules('Region').where({ province, city, area, street}).first();
        if (check) {
            throw new Error('辖区已存在');
        }

        let t = await db.transaction();
        try{
            let data = await this.modules('Region').insert($_POST, {transaction: t});
            if(account_ids && _.isArray(account_ids) && account_ids.length > 0){
                let results = []
                for(let account_id of account_ids){
                    results.push({
                        region_id: data.id,
                        account_id
                    })
                }
                await this.modules('Account.AccountRegion').bulkCreate(results, {transaction: t});
            }
            await t.commit();
            return true;
        } catch (error) {
            await t.rollback();
            throw new Error("保存失败");
        }
    }

    /**
     * 编辑辖区
     * @return {[type]} [description]
     */
    async actionUpdate() {
        let {id, province, city, area, street, account_ids} = $_POST;
        let checkExist = await this.modules('Region').where({id}).first();
        if (!checkExist) {
            throw new Error('辖区不存在');
        }

        let check = await this.modules('Region').where({province, city, area, street}).first();
        if (check && check.id != id) {
            throw new Error('辖区不能重复');
        }

        let t = await db.transaction();
        try{
            await this.modules('Region').where({ id }).update($_POST, {transaction: t});
            if(account_ids && _.isArray(account_ids) && account_ids.length > 0){
                await this.modules('Account.AccountRegion').where({ region_id: id}).destroy({transaction: t});
                let results = []
                for(let account_id of account_ids){
                    results.push({
                        region_id: id,
                        account_id
                    })
                }
                await this.modules('Account.AccountRegion').bulkCreate(results, {transaction: t});
            }else{
                await this.modules('Account.AccountRegion').where({ region_id: id}).destroy({transaction: t});
            }

            await t.commit();
            return true;
        } catch (error) {
            await t.rollback();
            throw new Error("保存失败");
        }
    }

    /**
     * 删除辖区
     * @return {[type]} [description]
     */
    async actionDelete() {
        let {id} = $_POST;
        super._validateRegion(id)

        let t = await db.transaction();
        try{
            await this.modules('Region').where({ id }).destroy({transaction: t});
            await this.modules('Account.AccountRegion').where({region_id: id}).destroy({transaction: t})
            await t.commit();
            return true;
        } catch (error) {
            await t.rollback();
            throw new Error("修改失败");
        }
    }

}

export default AdminRegionController;